import request from "@/utils/request";
import store from "@/store/index";
import router from "@/router/index";
// import store from "@/store/index";
//为user封装接口函数(用户登录接口)
export const login = (data) => {
  return request({
    method: "POST",
    url: "/front/user/login",
    //发送数据
    data: `phone=${data.phone}&password=${data.password}`,
  });
};

//用户信息接口(用户的头像和名称)
export const getUserInfo = () => {
  return request({
    method: "GET",
    url: "/front/user/getInfo",
    // headers: {
    //   Authorization: store.state.tokenInfo?.access_token,
    // },
  });
};

//用户退出登录
export const logout = () => {
  return request({
    method: "POST",
    url: "/front/user/logout",
  });
};

//刷新token
let promiseRT = null; //保存请求刷新token的promise对象
let refreshing = false; //标识是否已经启动了刷新动作
export const refreshToken = () => {
  if (refreshing) {
    return promiseRT;
  }
  refreshing = true;
  promiseRT = request({
    method: "POST",
    url: "/front/user/refresh_token",
    params: {
      refreshtoken: store.state.tokenInfo.refresh_token,
    },
  })
    .then((res) => {
      if (res.data.success) {
        //成功拿到新token(保存)
        store.commit("saveTokenInfo", res.data.content);
      } else {
        //没有拿到新token
        router.push({
          name: "login",
          query: { redirect: router.currentRoute.fullPath },
        });
        throw new Error("刷新token失败!");
      }
    })
    .finally(() => {
      refreshing = false; //重置标识位
    });
  return promiseRT;
};

//分页查询所有用户
export const queryUsers = (data = {}) => {
  return request({
    method: "POST",
    url: "/boss/user/getUserPages",
    data,
  });
};

//启用用户(接口需要传userId)
export const enableUser = (userId) => {
  return request({
    method: "GET",
    url: "/boss/user/enableUser",
    //query方式
    params: {
      userId,
    },
  });
};

//封禁用户
export const forbidUser = (userId) => {
  return request({
    method: "POST",
    url: "/boss/user/forbidUser",
    //json的格式
    data: { userId },
  });
};

//获取用户拥有的角色信息.返回所有角色,用户拥有的会被标记为true
export const getUserRoles = (userId) => {
  return request({
    method: "GET",
    url: "/boss/role/getRolesWithUserPermission",
    params: {
      userId,
    },
  });
};
//给指定用户分配角色
export const allocateUserRole = (data = {}) => {
  return request({
    method: "POST",
    url: "/boss/role/allocateUserRoles",
    data,
  });
};
